package org.koyad.portal.actions;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.koyad.portal.annotations.Action;
import org.koyad.portal.annotations.Action.Forward;
import org.koyad.portal.api.BaseAction;
import org.koyad.portal.context.PistonContext;
import org.koyad.portal.db.PistonDBManager;
import org.koyad.portal.db.DBObjectsWrapper;
import org.koyad.portal.misc.PortalPage;
import org.koyad.portal.tags.ViewRoot;
import org.koyad.portal.utils.LogUtils;
import org.koyad.portal.vo.PageMetaData;

@Action(
	name = "retrievePages",
	forwards = { 
					@Forward(name = "success", path = "/jsp/success.jsp"),
					@Forward(name = "failure", path = "/jsp/failure.jsp")
			   }
)
public class RetrievePagesAction extends BaseAction {

	private static final LogUtils LOGGER = LogUtils.getLogger(RetrievePagesAction.class);
	
	@Override
	public void execute() {
		
		String query = "SELECT * FROM PAGE WHERE INTERNAL = 'N'";
		DBObjectsWrapper dbObjectsWrapper = PistonDBManager.executeQuery(query);
		
		List<PortalPage> portalPages = new ArrayList<PortalPage>();
		PortalPage portalPage = null;
		try {
			ResultSet rs = dbObjectsWrapper.getResultSet();
			while(rs.next()) {
					String pageName = rs.getString("PAGE_NAME");
					String pageId = rs.getString("PAGE_ID");
					String pageMapping = rs.getString("PAGE_MAPPING");
					boolean proted = false;
					if(rs.getString("PROTECTED").equals("Y")) {
						proted = true;
					}
					String frame = rs.getString("FRAME");
					
					portalPage = new PortalPage(pageName, pageId, pageMapping, proted, frame, false);
					portalPages.add(portalPage);
			}
		} catch (SQLException e) {
			LOGGER.logException(e);
		} finally {
			PistonDBManager.close(dbObjectsWrapper);
		}
		
		PistonContext.getContext().getRequest().setAttribute("pageList", portalPages);
		
		ViewRoot viewRoot = PistonContext.getContext().getViewRoot();
		PageMetaData metaData = viewRoot.getMetaData();
		createView("/frames/" + metaData.getPortalPage().getFrame() + "/navigation.xml");
	}

}
